package com.arpa.ntocc.common.service.impl;

import cn.hutool.core.util.IdUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.dto.FileInfoDTO;
import com.arpa.ntocc.common.domain.entity.FileInfo;
import com.arpa.ntocc.common.domain.enums.FileInfoType;
import com.arpa.ntocc.common.domain.vo.FileInfoVO;
import com.arpa.ntocc.common.mapper.FileInfoMapper;
import com.arpa.ntocc.common.service.IFileInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2019-12-17
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {

    /**
     * 保存
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public boolean save(FileInfo entity) {
        if(StringUtils.isBlank(entity.getCode())){
            entity.setCode(IdUtil.simpleUUID());
        }
        if(StringUtils.isBlank(entity.getCreatedBy())){
            entity.setCreatedBy(UserUtil.getCode());
        }
        return super.save(entity);
    }

    /**
     * 根据code更新实体
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public int updateByCode(FileInfo entity) {
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
        }
        return baseMapper.update(entity,new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getCode,entity.getCode()));
    }

    /**
     * 查询列表
     * @param fileInfoDTO
     * @return
     */
    @Override
    public List<FileInfoVO> queryList(FileInfoDTO fileInfoDTO){
        //排序字段名需要驼峰转数据库下划线类型字段名
        if(StringUtils.isNotEmpty(fileInfoDTO.getSortField())){
            fileInfoDTO.setSortField(CommonUtil.camel2Underline(fileInfoDTO.getSortField()));
        }
        List<FileInfoVO> fileInfoVOList = baseMapper.queryList(fileInfoDTO);
        return fileInfoVOList;
    }

    /**
     * 查询合计,包含总数
     * @param fileInfoDTO
     * @return
     */
    @Override
    public FileInfoVO queryListSum(FileInfoDTO fileInfoDTO){
        FileInfoVO fileInfoVO = baseMapper.queryListSum(fileInfoDTO);
        return fileInfoVO;
    }

    /**
     * 保存图片信息
     * @param linkCode
     * @param fileType
     * @param url
     * @param deleteOld
     * @return
     */
    @Override
    public String save(String linkCode, FileInfoType fileType, String url, boolean deleteOld) {
        if(StringUtils.isEmpty(url)){
            throw new ServiceException("保存图片地址不能为空");
        }
        if(deleteOld){
            baseMapper.delete(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getType,fileType.getCode()).eq(FileInfo::getLinkCode,linkCode));
        }
        FileInfo entity = new FileInfo();
        entity.setCode(IdUtil.simpleUUID());
        entity.setBranchCode(UserUtil.getBranchCode());
        entity.setLinkCode(linkCode);
        entity.setType(fileType.getCode());
        entity.setUrl(url);
        entity.setFormat(CommonUtil.fileSuffix(url));
        entity.setRemark(fileType.getRemark());
        entity.setCreatedBy(UserUtil.getCode());
        entity.setGmtCreated(LocalDateTime.now());
        baseMapper.insert(entity);
        return entity.getCode();
    }

    /**
     * @Description  保存图片信息
     * @param linkCode
     * @param imgType
     * @param urls
     * @Date 2019/12/4 11:13
     * @Author wangkf
     * @return java.util.List<com.arpa.ntocc.common.domain.entity.ImageInfo>
     */
    @Override
    public List<FileInfo> saveList(String linkCode, FileInfoType imgType, String urls) {
        List<FileInfo> imageInfoDbs = baseMapper.selectList(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getLinkCode,linkCode).eq(FileInfo::getType,imgType.getCode()).eq(FileInfo::getDeleted,0));
        List<FileInfo> imageInfoList = new ArrayList<FileInfo>();
        String[] imgUrl = urls.split(",");
        int oldImgSize = imageInfoDbs.size();
        if (oldImgSize > imgUrl.length) {
            baseMapper.delete(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getType,imgType.getCode()).eq(FileInfo::getLinkCode,linkCode));
        }
        for (int i = 0,len = imgUrl.length; len > i; i++) {
            FileInfo entity = imageInfoDbs.isEmpty() || imageInfoDbs.size()-1 < i ? null : imageInfoDbs.get(i);
            if (entity == null) {
                entity = new FileInfo();
                entity.setCode(IdUtil.simpleUUID());
                entity.setBranchCode(UserUtil.getBranchCode());
                entity.setLinkCode(linkCode);
                entity.setCreatedBy(UserUtil.getCode());
                entity.setGmtCreated(LocalDateTime.now());
            } else {
                entity.setModifiedBy(UserUtil.getCode());
            }
            entity.setType(imgType.getCode());
            entity.setUrl(imgUrl[i]);
            entity.setFormat(CommonUtil.fileSuffix(imgUrl[i]));
            entity.setRemark(imgType.getRemark());
            entity.setDeleted(0);
            entity.setLinkCode(linkCode);
            imageInfoList.add(entity);
        }
        if (!super.saveOrUpdateBatch(imageInfoList)){
            throw new ServiceException("图片信息保存失败");
        }
        return imageInfoList;
    }

    /**
     * @Description  保存图片信息
     * @param linkCode
     * @param fileType
     * @param urlList
     * @Date 2019/12/4 11:13
     * @Author wangkf
     * @return java.util.List<com.arpa.ntocc.common.domain.entity.FileInfo>
     */
    public List<FileInfo> saveList(String linkCode, FileInfoType fileType, List<String> urlList) {
        List<FileInfo> imageInfoDbs = baseMapper.selectList(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getLinkCode,linkCode).eq(FileInfo::getType,fileType.getCode()).eq(FileInfo::getDeleted,0));
        List<FileInfo> imageInfoList = new ArrayList<FileInfo>();
        int oldImgSize = imageInfoDbs.size();
        if (oldImgSize > urlList.size()) {
            baseMapper.delete(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getType,fileType.getCode()).eq(FileInfo::getLinkCode,linkCode));
        }
        for (int i = 0,len = urlList.size(); len > i; i++) {
            FileInfo entity = imageInfoDbs.isEmpty() || imageInfoDbs.size()-1 < i ? null : imageInfoDbs.get(i);
            if (entity == null) {
                entity = new FileInfo();
                entity.setCode(IdUtil.simpleUUID());
                entity.setBranchCode(UserUtil.getBranchCode());
                entity.setLinkCode(linkCode);
                entity.setCreatedBy(UserUtil.getCode());
                entity.setGmtCreated(LocalDateTime.now());
            } else {
                entity.setModifiedBy(UserUtil.getCode());
            }
            entity.setType(fileType.getCode());
            entity.setUrl(urlList.get(i));
            entity.setFormat(CommonUtil.fileSuffix(urlList.get(i)));
            entity.setRemark(fileType.getRemark());
            entity.setDeleted(0);
            entity.setLinkCode(linkCode);
            imageInfoList.add(entity);
        }
        if (!super.saveOrUpdateBatch(imageInfoList)){
            throw new ServiceException("图片信息保存失败");
        }
        return imageInfoList;
    }

    /**
     * 根据linkCode和type获取图片地址list
     * @param linkCode
     * @param fileType
     * @Date 2019/12/19 9:33
     * @Author wangkf
     * @return java.util.List<java.lang.String>
    */
    public List<String> getFileUrl(String linkCode, FileInfoType fileType) {
        return baseMapper.getFileUtl(linkCode,fileType.getCode());
    }
}
